package com.hongri.recyclerview.fragment;

import java.util.List;

import android.animation.AnimatorInflater;
import android.animation.ObjectAnimator;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ClipDrawable;
import android.graphics.drawable.ScaleDrawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.LayoutAnimationController;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RemoteViews;
import android.widget.ScrollView;
import android.widget.TextView;
import com.facebook.rebound.SimpleSpringListener;
import com.facebook.rebound.Spring;
import com.facebook.rebound.SpringChain;
import com.facebook.rebound.SpringConfig;
import com.facebook.rebound.SpringSystem;
import com.hongri.recyclerview.R;
import com.hongri.recyclerview.activity.SettingActivity;
import com.hongri.recyclerview.adapter.DetailAndroidArtAdapter;
import com.hongri.recyclerview.adapter.DetailAndroidArtGridAdapter;
import com.hongri.recyclerview.adapter.DetailReboundAdapter;
import com.hongri.recyclerview.utils.DataUtil;
import com.hongri.recyclerview.utils.Logger;
import com.hongri.recyclerview.utils.ToastUtil;
import com.hongri.recyclerview.widget.CustomScrollView;

/**
 * @author：zhongyao on 2016/9/21 14:32
 * @description:Android 开发艺术探索
 */
public class DetailAndroidArtFragment extends Fragment implements DetailAndroidArtAdapter.onItemViewClickListener {

    private static final String ANDROID_ART = "android_art";
    private static DetailAndroidArtFragment androidArtFragment;
    private RecyclerView rv;
    private Animation animation;
    private LayoutAnimationController controller;
    private Activity mActivity;
    private ScrollView scrollView;
    private LinearLayout secondPage;
    private DetailAndroidArtAdapter mAdapter;
    private MyLocalReceiver receiver;
    private LinearLayout layout;
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mActivity = getActivity();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mActivity = null;
    }


    @Override
    public void onResume() {
        super.onResume();
        if (receiver == null){
            receiver = new MyLocalReceiver(mActivity,this);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (receiver != null){
            LocalBroadcastManager.getInstance(mActivity).unregisterReceiver(receiver);
        }
    }

    /**
     * LocalBroadcast的内部机制其实也是handler
     */
    private class MyLocalReceiver extends BroadcastReceiver{
        private Context context;
        private Fragment fragment;

        public MyLocalReceiver(Context context, DetailAndroidArtFragment fragment) {
            this.context = context;
            this.fragment = fragment;

            IntentFilter filter = new IntentFilter();
            filter.addAction(ANDROID_ART);
            LocalBroadcastManager.getInstance(mActivity).registerReceiver(this,filter);

        }

        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()){
                case ANDROID_ART:
                    ToastUtil.ShowBottomShort(context,R.string.android_art);
                    break;
            }

        }
    }


    public static DetailAndroidArtFragment newInstance(int position, String title) {
        if (androidArtFragment == null) {
            androidArtFragment = new DetailAndroidArtFragment();
        }
        return androidArtFragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_detail_andorid_art,container,false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        rv = (RecyclerView) view.findViewById(R.id.rv);

        /**
         * 除了在XML中指定LayoutAnimation外，还可以通过LayoutAnimationController来实现
         * BEGIN
         */
//        animation = AnimationUtils.loadAnimation(mActivity,R.anim.anim_item);
//        controller = new LayoutAnimationController(animation);
//        controller.setDelay(0.5f);
//        controller.setOrder(LayoutAnimationController.ORDER_NORMAL);
//        rv.setLayoutAnimation(controller);
        /**
         * END
         */

        scrollView = (ScrollView) view.findViewById(R.id.scrollView);
        secondPage = (LinearLayout) view.findViewById(R.id.secondPage);

        rv.setLayoutManager(new LinearLayoutManager(mActivity,LinearLayoutManager.VERTICAL,false));
        mAdapter = new DetailAndroidArtAdapter(mActivity, DataUtil.getAndroidArtData());
        mAdapter.setOnItemViewClickListener(this);
        rv.setAdapter(mAdapter);
    }

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public void itemOnClick(View view, final int position) {
        ToastUtil.ShowBottomShort(mActivity,DataUtil.getAndroidArtData().get(position));
        if (position == 0){
            //Animation
            View v = LayoutInflater.from(getActivity()).inflate(R.layout.android_art_animation, null);
            rv.setVisibility(View.GONE);
            scrollView.setVisibility(View.VISIBLE);
            secondPage.addView(v);

            //ImageView iv_animation = (ImageView) v.findViewById(R.id.iv_animation);
            //ImageView iv_frame = (ImageView) v.findViewById(R.id.iv_frame);
            TextView textView = (TextView) v.findViewById(R.id.tv);
            ImageView iv_animator = (ImageView) v.findViewById(R.id.iv_animator);



            //补间动画(View动画)
            //Animation animation = AnimationUtils.loadAnimation(mActivity,R.anim.animation_view);
            //iv_animation.startAnimation(animation);

            //逐帧动画
            //iv_frame.setBackgroundResource(R.drawable.frame_animation);
            //AnimationDrawable drawable = (AnimationDrawable) iv_frame.getBackground();
            //drawable.start();

            //将一个值从0平滑过渡到1
            //ValueAnimator valueAnimator = ValueAnimator.ofFloat(0f,1f);
            //valueAnimator.setDuration(3*1000);
            //valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            //    @Override
            //    public void onAnimationUpdate(ValueAnimator animation) {
            //        float animationValue = (float) animation.getAnimatedValue();
            //        Logger.d("值0过渡到1的值："+animationValue);
            //    }
            //});
            //valueAnimator.start();

            //ObjectAnimator animator = ObjectAnimator.ofFloat(textView,"rotationX",0.0f,360.0f);
            //animator.setDuration(4000);
            //animator.start();
            /**
             先进来，然后同时旋转和渐变（代码实现属性动画）
             */
            //ObjectAnimator fadeInOut = ObjectAnimator.ofFloat(textView,"alpha",1f,1f,1f);
            //ObjectAnimator rotate = ObjectAnimator.ofFloat(textView,"rotation",0f,0f);
            //ObjectAnimator moveIn = ObjectAnimator.ofFloat(textView,"translationX",-500f,0f);
            //AnimatorSet animatorSet = new AnimatorSet();
            //animatorSet.play(fadeInOut).with(rotate).after(moveIn);
            //animatorSet.setDuration(1*1000);
            ////动画监听
            //animatorSet.addListener(new Animator.AnimatorListener() {
            //    @Override
            //    public void onAnimationStart(Animator animation) {
            //        Logger.d("onAnimationStart");
            //    }
            //
            //    @Override
            //    public void onAnimationEnd(Animator animation) {
            //        Logger.d("onAnimationEnd");
            //    }
            //
            //    @Override
            //    public void onAnimationCancel(Animator animation) {
            //        Logger.d("onAnimationCancel");
            //    }
            //
            //    @Override
            //    public void onAnimationRepeat(Animator animation) {
            //        Logger.d("onAnimationRepeat");
            //    }
            //});
            ////动画监听（简化版）
            //animatorSet.addListener(new AnimatorListenerAdapter() {
            //    @Override
            //    public void onAnimationEnd(Animator animation) {
            //        super.onAnimationEnd(animation);
            //        Logger.d("onAnimaitonEnd--AnimatorListenerAdapter()");
            //
            //    }
            //});
            //animatorSet.start();

            //属性动画（.xml实现属性动画）
            //Animator animator = AnimatorInflater.loadAnimator(mActivity,R.animator.property_animator);
            //animator.setTarget(iv_animator);
            //animator.start();

            //ValueAnimator animator1 = (ValueAnimator)AnimatorInflater.loadAnimator(mActivity,R.animator.animator);
            //animator1.setTarget(iv_animator);
            //animator1.start();
            //
            //animator1.addUpdateListener(new AnimatorUpdateListener() {
            //    @Override
            //    public void onAnimationUpdate(ValueAnimator animation) {
            //        Logger.d("animation::"+animation.getAnimatedValue());
            //    }
            //});

            ObjectAnimator objectAnimator2 = (ObjectAnimator)AnimatorInflater.loadAnimator(mActivity,R.animator.object_animator_property_valueholder);
            objectAnimator2.setTarget(iv_animator);
            objectAnimator2.start();

            //AnimatorSet animatorSet1 = (AnimatorSet)AnimatorInflater.loadAnimator(mActivity,R.animator.property_animator2);
            //animatorSet1.setTarget(iv_animator);
            //
            //animatorSet1.addListener(new AnimatorListener() {
            //    @Override
            //    public void onAnimationStart(Animator animation) {
            //        Logger.d("onAnimationStart:"+animation);
            //    }
            //
            //    @Override
            //    public void onAnimationEnd(Animator animation) {
            //        Logger.d("onAnimationEnd:"+animation);
            //    }
            //
            //    @Override
            //    public void onAnimationCancel(Animator animation) {
            //        Logger.d("onAnimationCancel:"+animation);
            //    }
            //
            //    @Override
            //    public void onAnimationRepeat(Animator animation) {
            //        Logger.d("onAnimationRepeat:"+animation);
            //    }
            //});
            //animatorSet1.start();
        }else if (position == 1){
            /**
             * Android的Drawable
             */

            /**
             * 新增重点:GradientDrawable 2018-12-29
             * 通过<shape>标签创建的Drawable,其实体类实际上是GradientDrawable
             */
            //GradientDrawable drawable = new GradientDrawable();
            //drawable.setShape(GradientDrawable.RECTANGLE);
            //drawable.setCornerRadius(10);
            //imageView.setBackGround(drawable);

            //BitmapDrawable表示一张图片，开发中直接引用原始的图片即可，但是也可以通过XML的方式来描述它
            View v = LayoutInflater.from(getActivity()).inflate(R.layout.android_art_drawable, null);
            final ImageView iv_level = (ImageView) v.findViewById(R.id.iv_level);
            ImageView iv_transition = (ImageView) v.findViewById(R.id.iv_transition);
            ImageView iv_scale = (ImageView) v.findViewById(R.id.iv_scale);
            ImageView iv_clip = (ImageView) v.findViewById(R.id.iv_clip);
            LinearLayout ll_changeColor = (LinearLayout) v.findViewById(R.id.ll_changeColor);
            final TextView tv_changeColor = (TextView) v.findViewById(R.id.tv_changeColor);
//            ll_changeColor.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
////                    tv_changeColor.setDuplicateParentStateEnabled(true);
//                }
//            });
//            tv_changeColor.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    ToastUtil.ShowBottomShort(mActivity,"Text点击了");
////                    tv_changeColor.setDuplicateParentStateEnabled(false);
//                }
//            });
            rv.setVisibility(View.GONE);
            scrollView.setVisibility(View.VISIBLE);
            secondPage.addView(v);
            /**
             * LevelListDrawable
             * 根据不同的level，切换不同的Drawable
             */
            iv_level.post(new Runnable() {
                @Override
                public void run() {
                    {
                        for (int i=0;i<=1;i++) {
                            iv_level.setImageLevel(i);
                        }
                        try {
                            Thread.sleep(1*1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });

            /**
             * TransitionDrawable：
             * 用于实现两个Drawable之间的淡入淡出效果
             */
            TransitionDrawable drawable = (TransitionDrawable) getResources().getDrawable(R.drawable.transition_drawable);
            iv_transition.setImageDrawable(drawable);
            drawable.startTransition(3*1000);

            /**
             * ScaleDrawable:
             * 将Drawable缩放一定的比例
             */
            ScaleDrawable scaleDrawable = (ScaleDrawable) iv_scale.getBackground();
            scaleDrawable.setLevel(5000);

            /**
             * ClipDrawable:
             * 对Drawable进行裁剪(等级从0~10000，0表示完全裁剪)
             */
            ClipDrawable clipDrawable = (ClipDrawable) iv_clip.getDrawable();
            clipDrawable.setLevel(5000);
        }else if (position == 2) {
            View v = LayoutInflater.from(mActivity).inflate(R.layout.andorid_art_gridview,null,false);
            GridView gridview = (GridView) v.findViewById(R.id.gridview);
            rv.setVisibility(View.GONE);
            scrollView.setVisibility(View.VISIBLE);
            secondPage.addView(v);
            DetailAndroidArtGridAdapter adapter = new DetailAndroidArtGridAdapter(mActivity,DataUtil.getHomeData());
            gridview.setAdapter(adapter);
            gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                    ToastUtil.ShowBottomShort(mActivity,"ItemClick点击"+position);
                    Logger.d("gridItemClick0");
                }
            });

        }else if (position == 3) {
            View v = LayoutInflater.from(mActivity).inflate(R.layout.android_art_view,null,false);
//            RelativeLayout ll = (RelativeLayout) v.findViewById(R.id.ll);
//            CustomView customView = (CustomView) v.findViewById(R.id.customView);
//            Button btn = (Button) v.findViewById(R.id.btn);
//
//
//            ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) btn.getLayoutParams();
//            params.width +=500;
//            params.leftMargin +=300;
//            btn.requestLayout();
//            btn.setLayoutParams(params);
            rv.setVisibility(View.GONE);
            scrollView.setVisibility(View.VISIBLE);
            secondPage.addView(v);
        }else if (position == 5){
            LocalBroadcastManager.getInstance(mActivity).sendBroadcast(new Intent(ANDROID_ART));
        }else if (position == 4){
            View v = LayoutInflater.from(mActivity).inflate(R.layout.android_art_scroll_view,null,false);
            CustomScrollView customScrollView = (CustomScrollView) v.findViewById(R.id.customScrollView);
            rv.setVisibility(View.GONE);
            scrollView.setVisibility(View.VISIBLE);
            secondPage.addView(v);
            customScrollView.invalidate();
        }else if (position == 6){
            View v = LayoutInflater.from(mActivity).inflate(R.layout.android_art_rebound,null,false);
            final ImageView imageView = (ImageView) v.findViewById(R.id.imageView);
            layout = (LinearLayout) v.findViewById(R.id.layout);
            final HorizontalScrollView scrollView = (HorizontalScrollView) v.findViewById(R.id.scrollView);
            final RecyclerView recyclerView = (RecyclerView) v.findViewById(R.id.recyclerView);

            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    SpringSystem springSystem = SpringSystem.create();
                    Spring spring = springSystem.createSpring();
                    spring.setSpringConfig(SpringConfig.fromOrigamiTensionAndFriction(100,1));
                    spring.addListener(new SimpleSpringListener(){
                        @Override
                        public void onSpringUpdate(Spring spring) {
//                          super.onSpringUpdate(spring);
                            float value = (float) spring.getCurrentValue();
                            float scale = 1f - (value * 0.5f);
                            imageView.setScaleX(scale);
                            imageView.setScaleY(scale);
                        }
                    });
                    spring.setEndValue(1);
                }
            });

//            scrollView.setOnScrollChangeListener();

//            scrollView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
//                @Override
//                public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
//                    Logger.d("scrollView---onScrollchange");
//
//                    SpringChain springChain = SpringChain.create(40,6,50,7);
//                    int viewCount = layout.getChildCount();
//                    for (int i = 0; i < viewCount; i++) {
//                        final View viewChild = layout.getChildAt(i);
//                        springChain.addSpring(new SimpleSpringListener(){
//                            @Override
//                            public void onSpringUpdate(Spring spring) {
////                              super.onSpringUpdate(spring);
//                                viewChild.setTranslationX((float) spring.getCurrentValue());
//
//                            }
//                        });
//                    }
//
//                    List<Spring> springs = springChain.getAllSprings();
//                    for (int i = 0; i < springs.size(); i++) {
//                        springs.get(i).setCurrentValue(400);
//                    }
//                    springChain.setControlSpringIndex(2).getControlSpring().setEndValue(0);
//
//                }
//            });

            springAnim();

            layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    springAnim();
                }
            });
//            layout.setOnScrollChangeListener(new ViewG);
//            recyclerView.onScrollL

//            layout.setOnScrollChangeListener(new View.OnScrollChangeListener() {
//                @Override
//                public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
//
//                    Logger.d("onScrollChange");
//                    springAnim();
//                }
//            });

            recyclerView.setLayoutManager(new LinearLayoutManager(mActivity,LinearLayoutManager.HORIZONTAL,false));
            DetailReboundAdapter reboundAdapter = new DetailReboundAdapter(mActivity);
            recyclerView.setAdapter(reboundAdapter);

            recyclerView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    SpringChain springChain = SpringChain.create(40,6,50,7);
                    int viewCount = recyclerView.getChildCount();
                    for (int i = 0; i < viewCount; i++) {
                        final View viewChild = recyclerView.getChildAt(i);
                        springChain.addSpring(new SimpleSpringListener(){
                            @Override
                            public void onSpringUpdate(Spring spring) {
                                super.onSpringUpdate(spring);
                                viewChild.setTranslationX((float) spring.getCurrentValue());
                            }
                        });
                    }

                    List<Spring> springs = springChain.getAllSprings();

                    for (int i = 0; i < springs.size(); i++) {
                        springs.get(i).setCurrentValue(400);
                    }

                    springChain.setControlSpringIndex(2).getControlSpring().setEndValue(0);
                }
            });

            rv.setVisibility(View.GONE);
            scrollView.setVisibility(View.VISIBLE);
            secondPage.addView(v);
        }else if (position == 7) {
            View v = LayoutInflater.from(mActivity).inflate(R.layout.andorid_art_remote_views,null,false);
            Button btn_notification = (Button) v.findViewById(R.id.btn_notification);
            Button btn_notification_remoteViews = (Button) v.findViewById(R.id.btn_notification_remoteViews);

            //系统
            btn_notification.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    //1.构建一个打开Activity的PendingIntent
                    Intent intent=new Intent(getActivity(), SettingActivity.class);
                    PendingIntent mPendingIntent= PendingIntent.getActivity(getActivity(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
                    Notification mNotification = new Notification.Builder(mActivity)
                            .setContentIntent(mPendingIntent)
                            .setContentTitle("这是标题 ")
                            .setContentText("这是内容")
                            .setSmallIcon(R.drawable.ic_launcher)
                            .build();

                    NotificationManager manager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
                    manager.notify(0,mNotification);
                }
            });

            //remoteViews自定义
            btn_notification_remoteViews.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(),SettingActivity.class);
                    PendingIntent mPendingIntent = PendingIntent.getActivity(getActivity(),0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
                    RemoteViews remoteViews = new RemoteViews(getActivity().getPackageName(),R.layout.andorid_art_remote_views_view);
                    remoteViews.setTextViewText(R.id.title,"这是title");
                    remoteViews.setTextColor(R.id.title, Color.parseColor("#3366cc"));
//                    remoteViews.setTextViewTextSize(R.id.title,20,20);
                    remoteViews.setTextViewText(R.id.content,"这是content");
                    remoteViews.setTextColor(R.id.content,Color.parseColor("#FFEE3E22"));
//                    remoteViews.setTextViewTextSize(R.id.content,15,15);
                    remoteViews.setOnClickPendingIntent(R.id.title,mPendingIntent);

                    Notification mNotification = new Notification.Builder(mActivity)
                            .setContentIntent(mPendingIntent)
                            .setContent(remoteViews)
                            .setSmallIcon(R.drawable.ic_launcher)
                            .build();

                    NotificationManager manager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
                    manager.notify(0,mNotification);
                }
            });

            rv.setVisibility(View.GONE);
            scrollView.setVisibility(View.VISIBLE);
            secondPage.addView(v);
        }else if (position == 8){
            View view_gradient = LayoutInflater.from(mActivity).inflate(R.layout.android_art_gradient,null,false);
            rv.setVisibility(View.GONE);
            scrollView.setVisibility(View.VISIBLE);
            secondPage.addView(view_gradient);
        }

    }

    private void springAnim() {
        SpringChain springChain = SpringChain.create(40,6,50,7);
        int viewCount = layout.getChildCount();
        for (int i = 0; i < viewCount; i++) {
            final View viewChild = layout.getChildAt(i);
            springChain.addSpring(new SimpleSpringListener(){
                @Override
                public void onSpringUpdate(Spring spring) {
//                              super.onSpringUpdate(spring);
                    viewChild.setTranslationX((float) spring.getCurrentValue());

                }
            });
        }

        List<Spring> springs = springChain.getAllSprings();
        for (int i = 0; i < springs.size(); i++) {
            springs.get(i).setCurrentValue(400);
        }
        springChain.setControlSpringIndex(2).getControlSpring().setEndValue(0);

    }
}
